package com.pet.server.ext.action.user;

import java.util.Date;
import com.pet.server.ext.ActionBase;
import com.pet.server.ext.ApiError;
import com.pet.server.ext.Result;
import com.pet.server.ext.constants.BaseAttribute;
import com.pet.server.ext.data.UserInfo;
import com.pet.server.ext.data.VerificationCode;
import com.pet.server.ext.service.SystemService;
import com.pet.server.ext.service.UserService;
import com.pet.server.ext.util.DateUtil;
import com.pet.server.ext.util.NumberUtil;
import com.pet.server.ext.util.Parameters;
import com.pet.server.ext.util.StringUtil;
public class Phonebind extends ActionBase{
	public Integer user_id;
	public String phone_number,code;
	public VerificationCode vcode = null;
	public Phonebind(){
		 needCheckAuth =false;
	}

	@Override
	public void initParameters(Parameters params) throws ApiError {	
		user_id = NumberUtil.getInteger(params.getFieldValue("user_id"));
		phone_number=params.getFieldValue("phone_number");
	    code = params.getFieldValue("code");
	    if(StringUtil.isEmpty(user_id,phone_number,code)){
	    	throw ApiError.Type.INVALID_PARAM.toException();
	    }
	    SystemService systemService = new SystemService();
	    vcode = systemService.findVerification(phone_number);
	    if(null==vcode || !StringUtil.equals(vcode.getVerification_code(), code) || StringUtil.equals(BaseAttribute.LOGIC_TRUE, vcode.getIs_verified())){
	    	throw ApiError.Type.LOGIC_ERROR.toException("验证码错误!");
	    }
	    long distance = DateUtil.getMinByTwoDate(vcode.getSend_time(), new Date());
	    if(distance>30){
	    	throw ApiError.Type.LOGIC_ERROR.toException("验证码30分钟有效!");
	    }
	    systemService.updateVerification(vcode.getId());
	}
	@Override
	public Result invokeService() throws ApiError {
		UserService userService = new UserService();
		UserInfo u = userService.findUserInfoByPhoneNumber(phone_number);
		if(u!=null){
			throw ApiError.Type.LOGIC_ERROR.toException("手机号已经绑定账号!");
		}
		UserInfo user = userService.findUserInfoById(user_id);
        if(user==null||!StringUtil.isEmpty(user.phone_number)){
			throw ApiError.Type.LOGIC_ERROR.toException("绑定失败!");
        }		
		userService.updatePhoneNumber(phone_number, user_id);
        data.put("message", "绑定手机号成功!");
		Result result = new Result();
		result.put("data", data);
	    return result;
	}
}
